package com.ruoyi.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

@Component
public class RedisCache {

    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 判断 key 是否存在
     *
     * @param key 键
     * @return true 存在 false 不存在
     */
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    public <T> Long setCacheList(final String key, final List<Object> dataList) {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null? 0 : count;
    }

    public void addCacheList(final String key, String value) {
        redisTemplate.opsForList().rightPush(key, value);
    }

    public void addCacheList(final String key, Object value) {
        redisTemplate.opsForList().rightPushAll(key, value);
    }

    public <T> List<String> getCacheList(final String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 缓存Set
     *
     * @param key     缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, String> setCacheSet(final String key, final Set<String> dataSet) {
        BoundSetOperations<String, String> setOperation = redisTemplate.boundSetOps(key);
        Iterator<String> it = dataSet.iterator();
        while (it.hasNext()) {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    public Long addCacheSet(final String key, String value) {
        return redisTemplate.opsForSet().add(key, value);
    }

    /**
     * 获得缓存的Set
     *
     * @param key 键
     * @return
     */
    public <T> Set<String> getCacheSet(final String key) {
        return redisTemplate.opsForSet().members(key);
    }
}
